#include "led.h"
#include "delay.h"
#include "iap.h"
#include "usart2.h"
#include "usart1.h"
#include "devActivate.h"
#include "device_storage.h"
#include "modem.h"
static uint8_t ugManage_t = 0;
static uint8_t BootUpSio_t = 0;
static uint8_t crcSioBuf[32];
uint16_t crcPayLength = 0;
const char Software_Ver_Static[] __attribute__((at(BOOT_ADDR+0x400))) = "STF103VE-V1.2.7";
const char Hardware_Ver_Static[] __attribute__((at(BOOT_ADDR+0x410))) = BOOTSOF_VER;
const char CheckFile_Static[] __attribute__((at(BOOT_ADDR+0x420))) = "0000000000000000";
static void bootIAPUart1Callback(stcATBuff *getStcABuff)
{
	BootUpSio_t = SERIAL1;
	ugManage_t = replyProcessing(getStcABuff->DataBuff,(uint8_t)getStcABuff->DataBuff[PACK_CMD_INDEX],(uint16_t *)&(getStcABuff->length_t),1);
	if(getStcABuff->DataBuff[PACKET_CMD_INDEX] == UP_APP_FLASH_CRC){
		memcpy(crcSioBuf,getStcABuff->DataBuff,getStcABuff->length_t);
	}
	u1DataFrame_Send(getStcABuff->DataBuff,getStcABuff->length_t);	
}
static void bootIAPUart2Callback(stcATBuff *getStcABuff)
{
	BootUpSio_t = SERIAL2;
	ugManage_t = replyProcessing(getStcABuff->DataBuff,(uint8_t)getStcABuff->DataBuff[PACK_CMD_INDEX],(uint16_t *)&(getStcABuff->length_t),1);
	if(getStcABuff->DataBuff[PACKET_CMD_INDEX] == UP_APP_FLASH_CRC){
		memcpy(crcSioBuf,getStcABuff->DataBuff,getStcABuff->length_t);
	}
	u2DataFrame_Send(getStcABuff->DataBuff,getStcABuff->length_t);
}
int main(void){
	delay_init(72);
	hw_GPIO_Init();
	AT24CXX_Init();
//	registerHwEeprom_Write(AT24CXX_Write);
	activate_init();
	u1SetDmaRead_func(bootIAPUart1Callback);
	u2SetDmaRead_func(bootIAPUart2Callback);
	USART1_Init(115200);
//	USART2_Init(115200);
	registerHwFlash_Write(STMFLASH_Write);
	registerHwFlash_Read(STMFLASH_Read);
	registerHwFlash_Erase(STMFLASH_Erase);
//	if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_15)){
		bootCheckUpgrader();
		bootUpErrorFirCopyApp();
		bootCheckApp();
//	}
	STARBOT_BEEP_On();
	delay_ms(300);
	STARBOT_BEEP_Off();
//	if(!AT24CXX_Check()){
//		STARBOT_LED_RUN_On();
//	}
	while(1){
		for(int i = 0;i<3;i++){
			STARBOT_LED_STATUS_Toggle();
			delay_ms(300);
		}
		if(ugManage_t == UP_CMD_COPY_APP){
			crcSioBuf[PACKET_CMD_INDEX] = UP_BOOT_GOTO_APP;
			replyProcessing(crcSioBuf,CMD_UPGRADER,&crcPayLength,1);
			if(bootFirCopyApp()){
				crcSioBuf[PACKET_RESULT_INDEX]  = PACKET_ACK_OK;	
			}else{
				crcSioBuf[PACKET_RESULT_INDEX]  = PACKET_ACK_GoToApp_ERROR;	
			}
			switch(BootUpSio_t){
				case SERIAL1:
					u1DataFrame_Send(crcSioBuf,crcPayLength);
					break;
				case SERIAL2:
					u2DataFrame_Send(crcSioBuf,crcPayLength);
					break;
			}
			ugManage_t=0;
		}
	}
	return 0;
}

